import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { getToken, clearToken } from '@/utils/auth';

export const BASE_URL =(import.meta as any)?.env?.VITE_API_BASE_URL || '/api';

const instance: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  withCredentials: true,
  timeout: 15000,
});

instance.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    if (!config.headers) {
      // 兼容 AxiosHeaders/RawAxiosRequestHeaders 类型
      (config as any).headers = {};
    }
    (config.headers as any).Authorization = `Bearer ${token}`;
  }
  return config;
});

instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 后端统一返回 R 包装体，这里直接透传给调用方
    return response.data;
  },
  (error) => {
    const status = error?.response?.status;
    if (status === 401) {
      clearToken();
      // 可在这里发出事件或跳转登录页（当前无页面，不做跳转）
    }
    return Promise.reject(error);
  }
);

export function get<T = any>(url: string, config?: AxiosRequestConfig) {
  return instance.get<any, T>(url, config);
}

export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
  return instance.post<any, T>(url, data, config);
}

export function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
  return instance.put<any, T>(url, data, config);
}

export function del<T = any>(url: string, config?: AxiosRequestConfig) {
  return instance.delete<any, T>(url, config);
}
